import java.util.HashMap;


public class PeerInfo implements Comparable<PeerInfo> {

    private String peerID, address;
    private int port;

    private PeerInfo (HashMap<String, Object> peerDictionary) {
        super();
        port = 0;
        peerID = (String) peerDictionary.get("peer id");
        address = (String) peerDictionary.get("ip");
        port = (Integer) peerDictionary.get("port");
        if (peerID == null)
            peerID = "";
        if (address == null)
            address = "0.0.0.0";
    }

    public PeerInfo (String peerID, String IP, int port) {
        this.peerID = peerID;
        this.address = IP;
        this.port = port;
    }

    private PeerInfo (String peer) {
        super();
        peerID = "N/A";
        address = (peer.charAt(0) & 0xff) + "." + (peer.charAt(1) & 0xff)
        + '.' + (peer.charAt(2) & 0xff) + '.' + (peer.charAt(3) & 0xff);
        port =  (peer.charAt(4) & 0xff)*256 + (peer.charAt(5) & 0xff);
    }

    @SuppressWarnings("unchecked")
    public static PeerInfo createPeerInfo (Object obj) {
        if (obj instanceof HashMap)
            return new PeerInfo ((HashMap<String,Object>) obj);
        if (obj instanceof String)
            return new PeerInfo ((String) obj);
        return null;
    }

    public String toString () {
        return peerID + " " + address + " " + port;
    }

    public String peerID () {
        return peerID;
    }

    public String address () {
        return address;
    }

    public int port () {
        return port;
    }

    public void setPeerID (String peerID) {
        this.peerID = peerID;
    }

    public int compareTo(PeerInfo o) {
        int val = address.compareTo(o.address);
        if (val == 0) {
            val = o.port - port;
        }
        return val;
    }

    public boolean equals (Object obj) {
        if (!(obj instanceof PeerInfo))
            return false;
        return compareTo ((PeerInfo) obj) == 0;
    }
}
